package com.freely.ui.listener;

import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import com.freely.component.BaseViewHolder;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RVIDispatchEvent implements RecyclerView.OnItemTouchListener {
    private static final String TAG = "RVIDispatchEvent";
    private boolean disallowIntercept = false;
    private GestureDetector gestureDetector;
    private RVIOnGestureListener gestureListener = new RVIOnGestureListener();
    private OnItemClickListener clickListener;
    private BaseViewHolder viewHolder;
    private int position;

    public RVIDispatchEvent(OnItemClickListener onClickListener) {
        this.clickListener = onClickListener;
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
        Log.d(TAG, "onInterceptTouchEvent: 拦截"+e.getAction());
        onTouchEvent(rv, e);
        return true;
/*        if (disallowIntercept) {
            return false;
        }
        return false;*/
    }

    @Override
    public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
        Log.d(TAG, "onTouchEvent: ");
        System.currentTimeMillis();
        if (gestureDetector == null) {
            gestureDetector = new GestureDetector(rv.getContext(), gestureListener);
        }
        View view = rv.findChildViewUnder(e.getX(), e.getY());
        if (view == null) {
            Log.d(TAG, "onTouchEvent: 没找到视图");
            return;
        }
        position = rv.getChildAdapterPosition(view);
        viewHolder = (BaseViewHolder) rv.getChildViewHolder(view);
        gestureDetector.onTouchEvent(e);
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        Log.d(TAG, "onRequestDisallowInterceptTouchEvent: ");
        this.disallowIntercept = disallowIntercept;
    }

    private class RVIOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            Log.d(TAG, "onSingleTapUp: ");
            if (clickListener == null) {
                return false;
            }
            clickListener.onItemClick(viewHolder, position);
            return true;
        }
    }

    public interface OnItemClickListener {
        void onItemClick(BaseViewHolder viewHolder, int position);
    }

}
